//
//  BaseTextField.swift
//  OneMeeting
//
//  Created by zhangheng on 2019/8/8.
//  Copyright © 2019 www.zhangheng.com. All rights reserved.
//

import Foundation

@objc protocol BaseTextFieldDelegate {
    @discardableResult
    @objc optional func textFieldDidBecomeFirstResponder(senber:NSTextField) -> Bool
    @discardableResult
    @objc optional func textFieldDidResignFirstResponder(senber:NSTextField) -> Bool
    @objc optional func mouseDownTextFieldClicked(textField:NSTextField)
}

class BaseTextField: NSTextField {
    
    weak var baseDelegate:BaseTextFieldDelegate?
    
    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        self.zh_setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func zh_setupUI() {
        self.cell = self.zh_cell
        self.focusRingType = NSFocusRingType.none
        self.cell?.isEditable = true
        self.cell?.title = ""
        self.wantsLayer = true
        self.textColor = NSColor.black
    }
    
    lazy var zh_cell: VerCenteredTeFCell = {
        let cell = VerCenteredTeFCell()
        cell.isEditable = false
        cell.textColor = NSColor.white
        cell.font = NSFont.systemFont(ofSize: 12)
        return cell
    }()
    
    override func draw(_ dirtyRect: NSRect) {
        if window?.firstResponder == currentEditor() && NSApp.isActive {
            NSGraphicsContext.saveGraphicsState()
            NSFocusRingPlacement.only.set()
            NSGraphicsContext.restoreGraphicsState()
        } else {
            super.draw(dirtyRect)
        }
    }
    
    
    override func becomeFirstResponder() -> Bool {
        let success = super.becomeFirstResponder()
        if success {
            let textview = self.currentEditor() as? NSTextView
            textview?.insertionPointColor = NSColor.black
            if self.baseDelegate?.textFieldDidBecomeFirstResponder?(senber: self) != nil {
                return  (self.baseDelegate?.textFieldDidBecomeFirstResponder!(senber: self))!
            }
        }
        return success
    }
    
    override func resignFirstResponder() -> Bool {
        let success = super.resignFirstResponder()
        if success {
            if self.baseDelegate?.textFieldDidResignFirstResponder?(senber: self) != nil {
                return (self.baseDelegate?.textFieldDidResignFirstResponder!(senber: self))!
            }
        }
        return success
    }
 
    
    override func mouseDown(with event: NSEvent) {
        super.mouseDown(with: event)
        if self.baseDelegate?.mouseDownTextFieldClicked?(textField: self) != nil {
            self.baseDelegate?.mouseDownTextFieldClicked?(textField: self)
        }
    }
}
